<template>
  <div class="payment-management">
    <h2>我的支付记录</h2>

    <!-- 查询条件 -->
    <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top:10px">
<!--      <el-form-item label="支付记录ID">
        <el-input v-model="searchObj.id" placeholder="请输入支付记录ID" clearable/>
      </el-form-item>-->
      <el-form-item label="商品名称">
        <el-input v-model="searchObj.goods_name" placeholder="请输入商品名称" clearable/>
      </el-form-item>
<!--      <el-form-item label="支付方式">
        <el-select v-model="searchObj.payway" placeholder="请选择支付方式" clearable>
          <el-option label="支付宝" value="支付宝"></el-option>
          <el-option label="微信支付" value="微信支付"></el-option>
          <el-option label="银行卡" value="银行卡"></el-option>
        </el-select>
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" @click="handlerSearch">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 支付记录表格 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="goods_name" label="商品名称" width="200"></el-table-column>
      <el-table-column prop="payway" label="支付方式" width="200"></el-table-column>
      <el-table-column prop="price" label="支付金额" width="200">
        <template #default="scope">
          ¥{{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="pay_time" label="支付时间" width="250">
        <template #default="scope">
          {{ formatDateTime(scope.row.pay_time) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button
              size="small"
              type="primary"
              @click="viewPaymentDetail(scope.row)">
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :page-sizes="[10, 20, 50, 100]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 支付详情弹窗 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="支付详情"
        width="500px"
    >
      <el-form label-width="100px" v-if="selectedPayment">
        <el-form-item label="支付记录ID：">
          <span>{{ selectedPayment.id }}</span>
        </el-form-item>
        <el-form-item label="商品名称：">
          <span>{{ selectedPayment.goods_name }}</span>
        </el-form-item>
        <el-form-item label="支付方式：">
          <span>{{ selectedPayment.payway }}</span>
        </el-form-item>
        <el-form-item label="支付金额：">
          <span>¥{{ selectedPayment.price }}</span>
        </el-form-item>
        <el-form-item label="支付时间：">
          <span>{{ formatDateTime(selectedPayment.pay_time) }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import paymentApi from '@/api/payment_api.js'
import goodsApi from '@/api/goods_api.js'
import Login_api from "@/api/login_api.js"

// 表格数据
const tableData = ref([])
const total = ref(0)

// 用户ID
const userId = ref(null)

// 查询条件
const searchObj = ref({
  current: 1,
  limit: 10,
  id: '',
  user_id: null,
  goods_name: '',
  payway: ''
})

// 详情弹窗相关
const detailDialogVisible = ref(false)
const selectedPayment = ref(null)

// 页面加载完成后查询数据
onMounted(async () => {
  try {
    const userRes = await Login_api.logininfo()
    console.log("userRes", userRes);

    userId.value = userRes.id
    console.log("userId", userId.value);
    searchObj.value.user_id = userRes.id
    await search()
  } catch (error) {
    console.error("获取用户信息失败:", error)
    ElMessage.error("获取用户信息失败")
  }
})

// 查询支付记录列表
const search = async () => {
  try {
    let result;

    // 使用专门的根据用户ID查询支付记录的接口
    if (userId.value) {
      console.log('使用用户ID查询支付记录:', userId.value);
      // 先获取该用户的所有支付记录
      const allUserPayments = await paymentApi.getPaymentsByUserId(userId.value);
      console.log('用户所有支付记录:', allUserPayments);

      if (allUserPayments && Array.isArray(allUserPayments)) {
        // 过滤掉已删除的记录
        let filteredRecords = allUserPayments.filter(record => record.is_del !== 1);

        // 如果有商品名称查询条件，进行过滤
        if (searchObj.value.goods_name) {
          // 先确保所有记录都有商品名称
          for (let i = 0; i < filteredRecords.length; i++) {
            const payment = filteredRecords[i];
            if (!payment.goods_name && payment.goods_id) {
              try {
                const goodsResult = await goodsApi.getGoodsById(payment.goods_id);
                if (goodsResult && goodsResult.name) {
                  payment.goods_name = goodsResult.name;
                } else if (goodsResult && goodsResult.data && goodsResult.data.name) {
                  payment.goods_name = goodsResult.data.name;
                }
              } catch (error) {
                console.error('获取商品信息失败:', error);
              }
            } else if (!payment.goods_name && payment.seckill_goods_id) {
              try {
                const goodsResult = await goodsApi.getGoodsById(payment.seckill_goods_id);
                if (goodsResult && goodsResult.name) {
                  payment.goods_name = goodsResult.name;
                } else if (goodsResult && goodsResult.data && goodsResult.data.name) {
                  payment.goods_name = goodsResult.data.name;
                }
              } catch (error) {
                console.error('获取秒杀商品信息失败:', error);
              }
            }
          }

          // 根据商品名称过滤
          filteredRecords = filteredRecords.filter(payment =>
              payment.goods_name && payment.goods_name.includes(searchObj.value.goods_name)
          );
        }

        // 实现分页
        const start = (searchObj.value.current - 1) * searchObj.value.limit;
        const end = start + searchObj.value.limit;
        const pagedRecords = filteredRecords.slice(start, end);

        result = {
          records: pagedRecords,
          total: filteredRecords.length,
          current: searchObj.value.current,
          size: searchObj.value.limit,
          pages: Math.ceil(filteredRecords.length / searchObj.value.limit)
        };

        console.log('分页结果:', result);
      } else {
        result = {
          records: [],
          total: 0,
          current: searchObj.value.current,
          size: searchObj.value.limit,
          pages: 0
        };
      }
    } else {
      // 如果没有用户ID，则使用原来的分页查询（这不应该发生）
      const queryParams = { ...searchObj.value };
      queryParams.user_id = userId.value;
      console.log('发送的查询参数:', queryParams);
      result = await paymentApi.getPaymentPage(queryParams, searchObj.value.current, searchObj.value.limit);
    }

    // 设置表格数据
    if (result && result.records) {
      // 确保所有记录都有商品名称
      for (let i = 0; i < result.records.length; i++) {
        const payment = result.records[i];
        if (!payment.goods_name && payment.goods_id) {
          try {
            const goodsResult = await goodsApi.getGoodsById(payment.goods_id);
            if (goodsResult && goodsResult.name) {
              payment.goods_name = goodsResult.name;
            } else if (goodsResult && goodsResult.data && goodsResult.data.name) {
              payment.goods_name = goodsResult.data.name;
            }
          } catch (error) {
            console.error('获取商品信息失败:', error);
          }
        } else if (!payment.goods_name && payment.seckill_goods_id) {
          try {
            const goodsResult = await goodsApi.getGoodsById(payment.seckill_goods_id);
            if (goodsResult && goodsResult.name) {
              payment.goods_name = goodsResult.name;
            } else if (goodsResult && goodsResult.data && goodsResult.data.name) {
              payment.goods_name = goodsResult.data.name;
            }
          } catch (error) {
            console.error('获取秒杀商品信息失败:', error);
          }
        }
      }

      // 如果有商品名称查询条件，进行二次过滤
      if (searchObj.value.goods_name) {
        result.records = result.records.filter(payment =>
            payment.goods_name && payment.goods_name.includes(searchObj.value.goods_name)
        );
        result.total = result.records.length;
      }
    }

    tableData.value = (result && result.records) || []
    total.value = (result && result.total) || 0
  } catch (error) {
    console.error('查询支付记录列表时出错:', error)
    ElMessage.error("查询支付记录列表失败: " + (error.message || "未知错误"))
    tableData.value = []
    total.value = 0
  }
}



// 重置查询条件
const resetSearch = () => {
  searchObj.value.id = ''
  searchObj.value.goods_name = ''
  searchObj.value.payway = ''
  searchObj.value.current = 1
  search()
}

// 分页大小改变
const handleSizeChange = () => {
  search()
}

// 当前页改变
const handleCurrentChange = () => {
  search()
}

// 处理查询
const handlerSearch = () => {
  searchObj.value.current = 1
  search()
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  return dateTimeStr.replace('T', ' ')
}

// 查看支付详情
const viewPaymentDetail = (row) => {
  selectedPayment.value = { ...row }
  detailDialogVisible.value = true
}
</script>

<style scoped>
.payment-management {
  padding: 20px;
  background-color: #fff;
}

.payment-management h2 {
  margin-bottom: 20px;
}

.demo-form-inline {
  margin-bottom: 20px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}
</style>
